package com.mars.designpatterns.prototype.clone;

import com.mars.designpatterns.singleton.HungrySingleton;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * author by: mars
 * Date: 2022/2/7 9:32
 * Description:
 */
public class PigTest {
    public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //Date birthday = new Date(0L);
        //Pig pig1 = new Pig("佩奇",birthday);
        //Pig pig2 = (Pig) pig1.clone();
        //System.out.println(pig1);
        //System.out.println(pig2);
        //
        //// 修改pig1的生日,pig2的生日也被修改了，因为引用的Date是同一个对象，浅克隆
        //pig1.getBirthday().setTime(1644197901000L);
        //System.out.println(pig1);
        //System.out.println(pig2);


        // 破坏单例模式 HungrySingleton 实现 Cloneable 接口
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
        // 利用反射调用clone方法，获取返回值对象
        Method method = hungrySingleton.getClass().getDeclaredMethod("clone");
        method.setAccessible(true);
        // 获取clone对象
        HungrySingleton cloneHungrySingleton = (HungrySingleton)method.invoke(hungrySingleton);
        // 结果发现：单例 被 原型clone 破坏
        // 解决方式：一、不要实现  Cloneable 接口 ，或者 二、clone方法直接返回 getInstance()
        System.out.println(hungrySingleton); // com.mars.designpatterns.singleton.HungrySingleton@38af3868
        System.out.println(cloneHungrySingleton); // com.mars.designpatterns.singleton.HungrySingleton@77459877

    }
}
